package gu;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.table.*;

public class SiteChecker9 extends JFrame implements ActionListener, ItemListener, FocusListener {
	private static final long serialVersionUID = 1L;
	JTextField tx_domain=null, tx_spage=null, tx_exceptpage=null, tx_pageext=null,
				tx_loginurl=null, tx_formid=null, 
				tx_idtag=null, tx_idvalue=null, tx_pwtag=null, tx_pwvalue=null;
	private JTable resultTable=null;	
	private ButtonGroup loginGroup=null;
	private JLabel statusLabel=null;
	private progressDialog9 progressDialog=null;
	private checkLink9 checkLink=null;
	
	public static void main(String[] args) {
		new SiteChecker9();
	}
			
	public SiteChecker9() {
		super("SiteChecker9");
		setPreferredSize(new Dimension(640, 500));
		setLocation( 200, 200);
		Container contentPane = getContentPane();

		JPanel topPanel = new JPanel(new BorderLayout());
		topPanel.setPreferredSize(new Dimension(640, 240));
		  
		JPanel panel = new JPanel(new GridBagLayout());
		JPanel loginPanel = new JPanel(new FlowLayout());
		JPanel loginSub1  = new JPanel(new GridBagLayout());
		JPanel loginSub2  = new JPanel(new GridBagLayout());
		
		tx_spage = new JTextField(checkLink9.HTTP, 40);
		tx_spage.setToolTipText("Input full URL of start page of target domain : ex) http://www.test.com/a.jsp");

		tx_domain = new JTextField(checkLink9.HTTP, 40);
		tx_domain.setToolTipText("Input target domain address for restricting search range: ex) http://www.test.com");
		  
		tx_exceptpage = new JTextField(40);
		tx_exceptpage.setToolTipText("Input page name to except like 'logout.jsp'");

		tx_pageext = new JTextField(checkLink9.pageExt, 40);
		tx_pageext.setToolTipText("Input web page extension to extract URL from JavaScript");
		
		tx_domain.addFocusListener(this);
		tx_spage.addFocusListener(this);
		tx_exceptpage.addFocusListener(this);
		tx_pageext.addFocusListener(this);

		JButton runBtn = new JButton("Run");
		runBtn.addActionListener(this);

		GridBagConstraints gbc = new GridBagConstraints();
		gbc.anchor = GridBagConstraints.WEST;
		  
		addInput(panel, gbc, tx_spage,  "Start Page", 0, 0, true);
		addInput(panel, gbc, tx_domain, "Domain", 0, 1, true);
		addInput(panel, gbc, tx_exceptpage,"Except Page", 0, 2, true);
		addInput(panel, gbc, tx_pageext,"Page Extension", 0, 3, true);
		gbc.gridx=1; gbc.gridy=4;
		panel.add(runBtn, gbc);

		// log in
		loginGroup = new ButtonGroup();
		JRadioButton loginOpt1  = new JRadioButton("no need Login");
		JRadioButton loginOpt2  = new JRadioButton("call login form page");
		JRadioButton loginOpt3  = new JRadioButton("call login process page");
			
		addRadioInput(loginPanel, loginGroup, loginOpt1, checkLink9.LOGIN_NONE, true);
		addRadioInput(loginPanel, loginGroup, loginOpt2, checkLink9.LOGIN_FORM, false);
		addRadioInput(loginPanel, loginGroup, loginOpt3, checkLink9.LOGIN_PROCESS, false);
			
		tx_loginurl = new JTextField(checkLink9.HTTP, 40);
		tx_idtag 	= new JTextField(10);
		tx_idvalue 	= new JTextField(10);
		tx_pwtag 	= new JTextField(10);
		tx_pwvalue 	= new JTextField(10);
		tx_formid 	= new JTextField(10);

		addInput(loginSub1, gbc, tx_loginurl, "Login Page", 0, 0, false);
		addInput(loginSub2, gbc, tx_idtag, 	  "ID Tag Name", 0, 1, false);
		addInput(loginSub2, gbc, tx_idvalue,  "    ID Value", 2, 1, false);
		addInput(loginSub2, gbc, tx_pwtag, 	  "Password Tag Name", 0, 2, false);
		addInput(loginSub2, gbc, tx_pwvalue,  "    Password Value", 2, 2, false);
		addInput(loginSub2, gbc, tx_formid,   "Form ID (tag)", 0, 3, false);

		tx_formid.setToolTipText("ex) form1 in \"<form id='form1' ~~~>\"");
		
		// Table
		String colName[] = {"URL", "Title", "Response Code","Download Time"};
		DefaultTableModel model = new DefaultTableModel(colName,0);
		resultTable = new JTable(model);
		resultTable.setAutoCreateRowSorter(true);
		 
		contentPane.add(topPanel, BorderLayout.NORTH);
		topPanel.add(panel, BorderLayout.NORTH);
		topPanel.add(loginPanel, BorderLayout.CENTER);
		loginPanel.add(loginSub1);
		loginPanel.add(loginSub2);
		contentPane.add(new JScrollPane(resultTable),BorderLayout.CENTER);

		JPanel statusPanel = new JPanel();
		statusPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
		contentPane.add(statusPanel, BorderLayout.SOUTH);
		statusPanel.setPreferredSize(new Dimension(contentPane.getWidth(), 20));
		statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.X_AXIS));
		statusLabel = new JLabel("status");
		statusLabel.setHorizontalAlignment(SwingConstants.LEFT);
		statusPanel.add(statusLabel); 

		setDefaultCloseOperation(EXIT_ON_CLOSE);
		pack();
		setVisible(true);
	}
	
	public static void addInput(JPanel pn, GridBagConstraints gbc, JTextField tx, String label, int x, int y, boolean enabled) {
		gbc.gridx=x; gbc.gridy=y;
		pn.add(new JLabel(label), gbc);
			  
		gbc.gridx=x+1; gbc.gridy=y;
		pn.add(tx, gbc);
		tx.setEnabled(enabled);
	}
	public void addRadioInput(JPanel pn, ButtonGroup group, JRadioButton radio, String ActionCommand, boolean bool) {
		radio.setSelected(bool); 
		radio.addItemListener(this);
		radio.setActionCommand(ActionCommand);
		pn.add(radio);
		group.add(radio);
	} 
	/* ---------------------
	 * event
	 */
	@Override
	public void actionPerformed(ActionEvent arg0) {
		if (checkLink9.HTTP.equals(tx_spage.getText()) || "".equals(tx_spage.getText())) {
			msgbox("Input Start Web Page");
			return;
		}
		if (checkLink9.HTTP.equals(tx_domain.getText()) || "".equals(tx_domain.getText())) {
			msgbox("Input Target Domain address");
			return;
		}
		DefaultTableModel model = (DefaultTableModel) resultTable.getModel();
		resultTable.setAutoCreateRowSorter(false);
		model.getDataVector().removeAllElements();
		resultTable.setAutoCreateRowSorter(true);
		
		progressDialog = new progressDialog9(this);//(this, "Progress Dialog", true);
		
	    // start to find page
		checkLink = new checkLink9();
		checkLink.setFoundEvent(new foundEvent());
		
		checkLink.setTargetDomain(tx_domain.getText());
		checkLink.setStartURL(tx_spage.getText());
		checkLink.setExceptURL(tx_exceptpage.getText());
		checkLink.setPageExt(tx_pageext.getText());
		
		checkLink.setLoginURL(tx_loginurl.getText());
		checkLink.setLoginInfo(String.format("%s,%s,%s,%s", tx_idtag.getText(), tx_idvalue.getText(), tx_pwtag.getText(), tx_pwvalue.getText() ));
		checkLink.setFormID(tx_formid.getText());
		
		Thread t = new Thread(new Runnable() {
	        public void run() {
	    		checkLink.executeCheck(getSelectedRadio());
	        }
	    });
	    t.start();
	    // end in endFindDocuemnt() of foundEvent
	}
	@Override
	public void itemStateChanged(ItemEvent arg0) {
		String radio = getSelectedRadio();	
		tx_loginurl.setEnabled( ! checkLink9.LOGIN_NONE.equals(radio));
		tx_idtag.setEnabled( 	! checkLink9.LOGIN_NONE.equals(radio));
		tx_idvalue.setEnabled( 	! checkLink9.LOGIN_NONE.equals(radio));
		tx_pwtag.setEnabled( 	! checkLink9.LOGIN_NONE.equals(radio));
		tx_pwvalue.setEnabled( 	! checkLink9.LOGIN_NONE.equals(radio));
		tx_formid.setEnabled( 	  checkLink9.LOGIN_FORM.equals(radio));
	}
	/* ---------------------
	 * etc function
	 */
	private void msgbox(String s){
		JOptionPane.showMessageDialog(this, s);
	}
	private String getSelectedRadio(){
		ButtonModel model = (ButtonModel)loginGroup.getSelection();
		
		return model.getActionCommand();
	}
	
	@Override
    public void focusGained(FocusEvent e) {
        statusLabel.setText(((JTextField)e.getSource()).getToolTipText());
	}
	public void focusLost(FocusEvent e) {
        statusLabel.setText("");
        if (e.getSource()==tx_spage & "".equals(tx_domain.getText())) tx_domain.setText(checkLink9.HTTP+checkLink9.ExtractDomain(tx_spage.getText())+"/");
	}

	class foundEvent implements progressEvent9 {
		int total=0, badcnt=0;
		@Override
		public void findDocuemnt(String docName, linkInfo9 li) {
			progressDialog.SetMessage(docName, ++total);
			String arr[] = new String[4];
			DefaultTableModel model = (DefaultTableModel) resultTable.getModel();
			arr[0] = docName;
			arr[1] = li.getTitle();
			arr[2] = li.getResponseCode().toString();
			arr[3] = Long.toString(li.getResponseTime());
			model.addRow(arr);
			if (li.getResponseCode()!=200) badcnt++;
		}
		
		@Override
		public void endFindDocuemnt() {
			progressDialog.close();
			progressDialog=null;
			checkLink = null;
			statusLabel.setText(String.format("Found %s web pages, found %s bad links",total, badcnt));
		}
	}
}
